package uk.ac.cam.tcs40.sidnet.menu;

import java.util.LinkedList;
import java.util.List;

import uk.ac.cam.tcs40.sidnet.Hall;
import uk.ac.cam.tcs40.sidnet.R;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

public class MenuFragment extends Fragment {

	private List<MealAdapter> m_Adapters = new LinkedList<MealAdapter>();

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

		super.onCreateView(inflater, container, savedInstanceState);

		// Inflate the layout for this fragment
		final View view = inflater.inflate(R.layout.activity_menu, container, false);

		MealAdapter adapter;

		final ListView todayLunchListView = (ListView) view.findViewById(R.id.today_lunch_list);
		adapter = new MealAdapter(getActivity(), Hall.getInstance().getMenu().getTodayLunch());
		todayLunchListView.setAdapter(adapter);
		m_Adapters.add(adapter);

		final ListView todayDinnerListView = (ListView) view.findViewById(R.id.today_dinner_list);
		adapter = new MealAdapter(getActivity(), Hall.getInstance().getMenu().getTodayDinner());
		todayDinnerListView.setAdapter(adapter);
		m_Adapters.add(adapter);

		final ListView tomorrowLunchListView = (ListView) view.findViewById(R.id.tomorrow_lunch_list);
		adapter = new MealAdapter(getActivity(), Hall.getInstance().getMenu().getTomorrowLunch());
		tomorrowLunchListView.setAdapter(adapter);
		m_Adapters.add(adapter);

		final ListView tomorrowDinnerListView = (ListView) view.findViewById(R.id.tomorrow_dinner_list);
		adapter = new MealAdapter(getActivity(), Hall.getInstance().getMenu().getTomorrowDinner());
		tomorrowDinnerListView.setAdapter(adapter);
		m_Adapters.add(adapter);

		return view;
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		new DownloadMenuTask().execute();
	}

	private class DownloadMenuTask extends AsyncTask<Void, Void, Void> {
		protected void onPreExecute() {
		}

		protected Void doInBackground(Void... v) {
			if (!Hall.getInstance().haveDownloadedMenu())
				Hall.getInstance().downloadMenu();
			return null;
		}

		protected void onProgressUpdate(Void... progress) {
		}

		protected void onPostExecute(Void result) {
			for (MealAdapter adapter : m_Adapters)
				adapter.notifyDataSetChanged();
		}
	}
}
